﻿<%@ WebHandler Language="C#" Class="MyBankAndMoney" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using StarTech.DBUtility;
using System.Text;

/// <summary>
/// 我的资金接口（包括提现、绑定银行卡等功能）
/// </summary>
public class MyBankAndMoney : IHttpHandler {
    
    AdoHelper ado = AdoHelper.CreateHelper("DB_Instance");
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        bool isAuth = (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value)) ? true : false;

        if (isAuth == true)
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);
            
            if (flag == "listbank")
            {
                //我的银行卡列表信息
                context.Response.Write(ListBankCard(memberId));
                
            }
            else if (flag == "addbank")
            {
                //新增绑定银行卡
                string TrueName = HttpUtility.UrlDecode(Common.NullToEmpty(context.Request["TrueName"]));
                string CardNumber = Common.NullToEmpty(context.Request["CardNumber"]);
                string BankName = HttpUtility.UrlDecode(Common.NullToEmpty(context.Request["BankName"]));
                string BankDetailAddress = HttpUtility.UrlDecode(Common.NullToEmpty(context.Request["BankDetailAddress"]));
                string BandkAdressCode = Common.NullToEmpty(context.Request["BandkAdressCode"]);
                string BandkAdressCodeName = "广东省,深圳市";
                context.Response.Write(AddBank(memberId, TrueName, CardNumber, BankName, BankDetailAddress, BandkAdressCode, BandkAdressCodeName));

            }
            else if (flag == "delbank")
            {
                //解除银行卡绑定
                string CardNumber = Common.NullToEmpty(context.Request["CardNumber"]);
                context.Response.Write(DeleteBank(memberId, CardNumber));
            }
            else if (flag == "applycash")
            {
                //提现申请
                string TrueName= HttpUtility.UrlDecode(Common.NullToEmpty(context.Request["TrueName"]));
                string CardNumber=Common.NullToEmpty(context.Request["CardNumber"]);
                decimal Moeny=decimal.Parse(Common.NullToEmpty(context.Request["money"]));
                string pwd = Common.NullToEmpty(context.Request["c"]);
                string BinkInfo = HttpUtility.UrlDecode(Common.NullToEmpty(context.Request["BinkInfo"]));
                string pwd1 = Common.NullToEmpty(context.Request["pwd1"]);
                context.Response.Write(ApplyCash(pwd1,memberId, TrueName, CardNumber, BinkInfo, Moeny, DateTime.Now, "0", "", DateTime.Now, ""));
            } 
            if (flag == "myaccount")
            {
                //我的电子钱包余额
                context.Response.Write(GetMyAccountMoney());

            } 
            if (flag == "listaccount")
            {
                //我的电子钱包明细
                context.Response.Write(ListAccountMoneyDetail());

            }
            if (flag == "bindcard")
            {
                //我的银行卡
                context.Response.Write(BindCard(memberId));

            } 
            
            if (flag == "koumoney")
            {
                //扣费计算
                decimal Moeny = decimal.Parse(Common.NullToEmpty(context.Request["money"]));
                context.Response.Write(GetKouMoney(Moeny));

            }
            else if (flag == "")
            {

            }
        }
        
    }


    //[{"GoodsId":"100813","GoodsName":"房间专修","GoodsCode":"G102749","AddTime":"2016/7/26 20:35:45","JobStatus":"竞价中","priceCount":"0"},{"GoodsId":"100815","GoodsName":"任务标题任务标题任务标题","GoodsCode":"G102751","AddTime":"2016/8/6 17:15:03","JobStatus":"竞价中","priceCount":"0"},{"GoodsId":"100816","GoodsName":"11111111111111","GoodsCode":"G102752","AddTime":"2016/8/6 17:23:48","JobStatus":"竞价中","priceCount":"0"},{"GoodsId":"100817","GoodsName":"11天的水泥工，全包了","GoodsCode":"G102753","AddTime":"2016/8/6 18:42:41","JobStatus":"竞价中","priceCount":"0"}]

    /// <summary>
    /// 我的银行卡列表信息
    /// </summary>
    /// <param name="memberId"></param>
    protected string ListBankCard(string memberId)
    {
        string strSql = "select Sysnumber,BankName,CardNumber from T_Member_Bank where MemberId='" + memberId + "'";
        DataTable dt = ado.ExecuteSqlDataset(strSql).Tables[0];
        return JSONHelper.GetJSON(dt);
        //string josn = "[{\"Sysnumber\":\"f3e27969-6e1b-425a-b8ec-1ebf9da1611a\",\"BankName\":\"建设银行\",\"CardNumber\":\"1111111111111111111111\"},{\"Sysnumber\":\"75727969-6e1b-425a-b8ec-1ebf9da1611a\",\"BankName\":\"农业银行\",\"CardNumber\":\"22222222222222222222222\"}]";
        //return josn;
    }

    /// <summary>
    /// 我的银行卡列表信息select
    /// </summary>
    /// <param name="memberId"></param>
    protected string BindCard(string memberId)
    {
        string html = "";
        string strSql = "select * from T_Member_Bank where MemberId='" + memberId + "'";
        DataTable dt = ado.ExecuteSqlDataset(strSql).Tables[0];
        foreach (DataRow row in dt.Rows) 
        {
            string info = row["TrueName"] + "|" + row["CardNumber"] + "|" + row["BankDetailAddress"] + "|" + row["BandkAdressCodeName"];
            html += "<option value='" + info + "'>" + row["BankName"] + "," + row["CardNumber"] + "</option>";
        }
        return html;
    }
    
    /// <summary>
    /// 绑定银行卡号
    /// </summary>
    protected string AddBank(string MemberId, string TrueName, string CardNumber, string BankName, string BankDetailAddress, string BandkAdressCode, string BandkAdressCodeName)
    {
        StringBuilder strSql = new StringBuilder();
        strSql.Append("insert into T_Member_Bank(");
        strSql.Append("Sysnumber,MemberId,TrueName,CardNumber,BankName,BankDetailAddress,BandkAdressCode,BandkAdressCodeName)");
        strSql.Append(" values (");
        strSql.Append("@Sysnumber,@MemberId,@TrueName,@CardNumber,@BankName,@BankDetailAddress,@BandkAdressCode,@BandkAdressCodeName)");
        SqlParameter[] parameters = {
					new SqlParameter("@Sysnumber", SqlDbType.VarChar,50),
					new SqlParameter("@MemberId", SqlDbType.VarChar,50),
					new SqlParameter("@TrueName", SqlDbType.VarChar,50),
					new SqlParameter("@CardNumber", SqlDbType.VarChar,50),
					new SqlParameter("@BankName", SqlDbType.VarChar,500),
					new SqlParameter("@BankDetailAddress", SqlDbType.VarChar,500),
					new SqlParameter("@BandkAdressCode", SqlDbType.VarChar,50),
					new SqlParameter("@BandkAdressCodeName", SqlDbType.VarChar,500)};
        parameters[0].Value = Guid.NewGuid().ToString();
        parameters[1].Value = MemberId;
        parameters[2].Value = TrueName;
        parameters[3].Value = CardNumber;
        parameters[4].Value = BankName;
        parameters[5].Value = BankDetailAddress;
        parameters[6].Value = BandkAdressCode;
        parameters[7].Value = BandkAdressCodeName;

        int rows = ado.ExecuteSqlNonQuery(strSql.ToString(), parameters);
        if (rows > 0)
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }


    /// <summary>
    /// 解除银行卡绑定
    /// </summary>
    protected string DeleteBank(string memberId, string cardNumber)
    {
        string sql = "delete T_Member_Bank where MemberId='" + memberId + "' and CardNumber='" + cardNumber + "'";
        if (ado.ExecuteSqlNonQuery(sql) > 0)
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }

    /// <summary>
    /// 申请提现
    /// </summary>
    protected string ApplyCash(string pwd1, string MemberId, string TrueName, string CardNumber, string BankInfo, decimal Moeny, DateTime ApplayTime, string IfDeal, string DealAdmin, DateTime DealTime, string DealRemarks)
    {
        object objYE = ado.ExecuteSqlScalar("select account_money from T_Moneybag_AccountInfo where member_id='" + this.memberId + "'");
        string strYE = objYE == null ? "0" : objYE.ToString();
        if (Moeny > decimal.Parse(strYE))
        {
            return "余额不足";
        }

        pwd1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd1, "MD5");
        object checkPwd = ado.ExecuteSqlScalar("select memberId from T_Member_Info where memberId='" + this.memberId + "' and PasswordPay='" + pwd1 + "'");
        if (checkPwd == null) { return "交易密码错误"; }

        string sysnumber = Guid.NewGuid().ToString();
        StringBuilder strSql = new StringBuilder();
        strSql.Append("insert into T_Member_ApplayCashBank(");
        strSql.Append("Sysnumber,MemberId,TrueName,CardNumber,BankInfo,Moeny,ApplayTime,IfDeal,DealAdmin,DealTime,DealRemarks)");
        strSql.Append(" values (");
        strSql.Append("@Sysnumber,@MemberId,@TrueName,@CardNumber,@BankInfo,@Moeny,@ApplayTime,@IfDeal,@DealAdmin,@DealTime,@DealRemarks)");
        SqlParameter[] parameters = {
					new SqlParameter("@Sysnumber", SqlDbType.VarChar,50),
					new SqlParameter("@MemberId", SqlDbType.VarChar,50),
					new SqlParameter("@TrueName", SqlDbType.VarChar,50),
					new SqlParameter("@CardNumber", SqlDbType.VarChar,50),
					new SqlParameter("@BankInfo", SqlDbType.VarChar,500),
					new SqlParameter("@Moeny", SqlDbType.Decimal,9),
					new SqlParameter("@ApplayTime", SqlDbType.DateTime),
					new SqlParameter("@IfDeal", SqlDbType.VarChar,50),
					new SqlParameter("@DealAdmin", SqlDbType.VarChar,50),
					new SqlParameter("@DealTime", SqlDbType.DateTime),
					new SqlParameter("@DealRemarks", SqlDbType.VarChar,500)};
        parameters[0].Value = sysnumber; 
        parameters[1].Value = MemberId;
        parameters[2].Value = TrueName;
        parameters[3].Value = CardNumber;
        parameters[4].Value = BankInfo;
        parameters[5].Value = Moeny;
        parameters[6].Value = ApplayTime;
        parameters[7].Value = IfDeal;
        parameters[8].Value = DealAdmin;
        parameters[9].Value = DealTime;
        parameters[10].Value = DealRemarks;

        int rows = ado.ExecuteSqlNonQuery(strSql.ToString(), parameters);
        if (rows > 0)
        {
            //电子钱包记录
            MoneyBagTools.CreateMoneyBagDetail(MemberId, -Moeny, "xf", sysnumber);

            //电子钱包记录(平台扣费)
            decimal Moeny2 = Moeny * WebConfig.GetKouMoneySet();
            MoneyBagTools.CreateMoneyBagDetail(MemberId, -Moeny2, "xf2", sysnumber);
            return "1";
        }
        else
        {
            return "0";
        }
    }

    protected string GetKouMoney(decimal Moeny)
    {
        //电子钱包记录(平台扣费)
        decimal Moeny2 = Moeny * WebConfig.GetKouMoneySet();
        return Moeny2.ToString();
    }


    /// <summary>
    /// 我的电子钱包余额
    /// </summary>
    /// <returns></returns>
    protected string GetMyAccountMoney()
    {
        MoneyBagTools.AutoPay(this.memberId);
        
		 //update total
        ado.ExecuteSqlNonQuery("update T_Moneybag_AccountInfo set account_money=(select isnull(sum(money),0) from T_Moneybag_AccountDetail where account_id=(select account_id from T_Moneybag_AccountInfo where member_id='" + this.memberId + "'))");
			
        object objYE = ado.ExecuteSqlScalar("select account_money from T_Moneybag_AccountInfo where member_id='" + this.memberId + "'");
        string strYE = objYE == null ? "0" : objYE.ToString();

        object objLJ = ado.ExecuteSqlScalar("select isnull(sum(money),0) from T_Moneybag_AccountDetail where money>0 and account_id=(select account_id from T_Moneybag_AccountInfo where member_id='" + this.memberId + "')");
        string strLJ = objLJ == null ? "0" : objLJ.ToString();

        object objLJ2 = ado.ExecuteSqlScalar("select isnull(sum(money),0) from T_Moneybag_AccountDetail where money>0 and account_id=(select account_id from T_Moneybag_AccountInfo where member_id='" + this.memberId + "') and createtime>'" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-1'");
        string strLJ2 = objLJ2 == null ? "0" : objLJ2.ToString();

        return strYE + "|" + strLJ + "|" + strLJ2;
    }

    /// <summary>
    /// 我的电子钱包余额明细
    /// </summary>
    /// <returns></returns>
    protected string ListAccountMoneyDetail()
    {
        DataSet ds = ado.ExecuteSqlDataset("select * from T_Moneybag_AccountDetail where account_id=(select account_id from T_Moneybag_AccountInfo where member_id='" + this.memberId + "') order by createtime desc");
        return JSONHelper.GetJSON(ds.Tables[0]);
    }
    
    
    public bool IsReusable {
        get {
            return false;
        }
    }

}